package com.dengqi.mymodule.activity.glide.adapter;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.module.imagelib.glide.ImageLoader;
import com.module.imagelib.glide.strategy.GlideStrategy;
import com.module.imagelib.glide.ui.GlideView;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import androidx.viewpager.widget.PagerAdapter;

/**
 * viewpager展示多张图片用
 * imageview保持在3个，加1个删1个
 * Created by dell on 2018/6/28
 */

public class ViewPagerAdatper extends PagerAdapter {

    HashMap<Integer, ImageView> imgLists = new LinkedHashMap<>();
    List<String> strLists;
    Context mContext;

    public ViewPagerAdatper(Context mContext, List<String> strLists) {
        this.mContext = mContext;
        this.strLists = strLists;
    }

    @Override
    public int getCount() {
        return strLists.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        GlideView imageView = new GlideView(mContext);
        imageView.setBackgroundColor(Color.GRAY);

        ImageLoader.getInstance().setImageLoader(new GlideStrategy(mContext));
        ImageLoader.getInstance().load(String.format(strLists.get(position), position+1)).into(imageView);

        //mContext.getApplicationContext()比mContext垃圾回收效果好
//        GlideApp.with(mContext.getApplicationContext())
//                .load(String.format(strLists.get(position), position + 1))
//                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
//                .skipMemoryCache(false)
//                .dontAnimate()
//                .into(imageView);
//        imageView.url(String.format(strLists.get(position), position+1)).load();
        container.addView(imageView);
        imgLists.put(position, imageView);
        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ImageView imageView = imgLists.get(position);
        container.removeView(imageView);
        //保证imageview不被引用
        imgLists.remove(position);
    }
}
